(function ($) {
    function DetailView(target, options) {
        this.dbPath = G_Path.contextPath ? G_Path.contextPath : "";
        options = options || {};
        this.target = target;
        this.options = options;
        this.formName = this.options.form ? this.options.form : "mainForm";
        this.fieldInfo = options.fieldInfo ? options.fieldInfo : [];
        this.data = options.data ? options.data : [];
        this.toolsbarElement = null;
        this.containerElement = null;
        this.containerTitleElement = null;
        this.containerBodyElement = null;
        this.tableElement = null;
        this.formIndex = 0;
        this.data = [];
        this.init();
    }

    DetailView.DEFAULTS = {
        title: "设置可配送区域和运费",
        form: "detail",
        fieldInfo: [
            {
                "field": "goodsCount", "title": "可配送区域", type: "dialog", callback: function () {

            }
            },
            {"field": "logisticsName", "title": "首件(个)", type: "text"},
            {"field": "marketTime", "title": "运费", type: "double"}
        ]
    };
    $.extend(DetailView.prototype, {
        init: function () {
            var self = this;
            this.toolsbarElement = $('<div class="toolbar blue clearfix"></div>').appendTo(this.target);
            this.containerElement = $('<div class="panel panel-default"/>').appendTo(this.target);

            this.containerTitleElement = $('<div class="panel-title"></div>').appendTo(this.containerElement);
            this.containerBodyElement = $('<div class="panel-body"></div>').appendTo(this.containerElement);

            $('<input type="button" class="btn btn-primary" value="设置可配送区域和运费">').click(function (e) {
                self.addRecord();
            }).appendTo(this.containerTitleElement);

            this.draw();
        },
        initData: function () {
            if (this.data && this.data.length <= 0) {
                this.data = this.options.initData;
            }
            //添加记录
            for (var i = 0; i < this.data.length; i++) {
                this.addRecord(this.data[i]);
            }

        },
        getData: function () {
            var self = this;
            var url = this.options.url;
            if (url && url != "") {
                $.get(url, function (text) {
                    var page = $.parseJSON(text);
                    self.data = page.list;
                    self.initData();
                })
            }
            else {
                self.initData();
            }

        },
        addTitleRecord: function () {
            var fieldInfo = this.options.fieldInfo;
            if (fieldInfo) {
                var oRow = this.tableElement.insertRow(this.tableElement.rows.length);
                var r = this.tableElement.rows.length - 1;
                for (var i = 0; i < fieldInfo.length; i++) {
                    var field = fieldInfo[i];
                    var oCell = oRow.insertCell(oRow.cells.length);
                    if (field.title) {
                        oCell.innerHTML = field.title;
                    }
                    if (field.type && field.type == "hidden") {
                        oCell.style.display = "none";
                    }
                }

                //操作单元格
                var oCell = oRow.insertCell(oRow.cells.length);

            }
        },
        addRecord: function (model) {
            var self = this;
            var fieldInfo = this.options.fieldInfo;
            if (fieldInfo) {
                var oRow = this.tableElement.insertRow(this.tableElement.length);
                oRow.setAttribute("formIndex", this.formIndex);
                if (model && model.id != null) {
                    if (model.id) {
                        oRow.setAttribute("docId", model.id);
                    }
                }
                var r = this.tableElement.rows.length - 1;

                for (var i = 0; i < fieldInfo.length; i++) {
                    var col = fieldInfo[i];
                    var oCell = oRow.insertCell(oRow.cells.length);
                    if (col.field) {
                        var fieldName = col.field;
                        var fieldType = col.type;
                        var fieldValue = "";
                        if (model) {
                            if (model[fieldName]) {
                                fieldValue = model[fieldName];
                            }
                        }
                        switch (fieldType) {
                            case "dialog":
                                if (col.id) {
                                    var input = document.createElement("input");
                                    input.type = "hidden";
                                    input.name = this.formName + "[" + this.formIndex + "]." + col.id;
                                    input.setAttribute("field", col.id);

                                    if (model && model[col.id]) {
                                        input.value = model[col.id] ? model[col.id] : "";
                                    }
                                    oCell.appendChild(input);
                                }

                                var input = document.createElement("input");
                                input.type = "text";
                                input.name = this.formName + "[" + this.formIndex + "]." + fieldName;
                                input.setAttribute("field", fieldName);
                                input.className = "form-control";
                                input.value = fieldValue;
                                var fn = col.callback;
                                if (fn && $.isFunction(fn)) {
                                    $(input).click(function (e) {
                                        fn.call(self, $(this), model);
                                    });
                                }
                                oCell.appendChild(input);
                                break;
                            case "text":
                                var input = document.createElement("input");
                                input.type = "text";
                                input.name = this.formName + "[" + this.formIndex + "]." + fieldName;
                                input.setAttribute("field", fieldName);
                                input.className = "form-control";
                                input.value = fieldValue;
                                oCell.appendChild(input);
                                break;
                            case "hidden":
                                var input = document.createElement("input");
                                input.type = "hidden";
                                input.name = this.formName + "[" + this.formIndex + "]." + fieldName;
                                input.setAttribute("field", fieldName);
                                input.className = "form-control";
                                input.value = fieldValue;
                                oCell.appendChild(input);
                                oCell.style.display = "none";
                                break;
                            default :
                                var input = document.createElement("input");
                                input.name = this.formName + "[" + this.formIndex + "]." + fieldName;
                                input.setAttribute("field", fieldName);
                                input.type = "text";
                                input.className = "form-control";
                                input.value = fieldValue;
                                oCell.appendChild(input);
                                break;
                        }

                    }

                }
                //增加删除功能
                var oCell = oRow.insertCell(oRow.cells.length);
                $("<div class='glyphicon glyphicon-trash'></div>").click(function (e) {
                    self.deleteRecord(e);
                }).appendTo($(oCell));

                this.formIndex++;
            }

        },
        deleteRecord: function (e) {
            var oa = e.target;
            var otr = oa.parentElement;

            while (otr.tagName != "TR")
                otr = otr.parentElement;
            var id = otr.getAttribute("docid");

            this.tableElement.deleteRow(otr.rowIndex);
            this.refreshIndex();


        },
        deleteData: function (id) {
            if (id && id != "") {
                var url = this.options.deleteUrl;
                if (url && url != "") {
                    $.get(url + "/" + id, function (e) {

                    });
                }
            }
        },
        getRowElement: function (oa) {
            var otr = null;
            if (oa) {
                otr = oa.parentElement;
                while (otr.tagName != "TR")
                    otr = otr.parentElement;
            }

            return otr;
        },
        getRowFormIndex: function (oa) {
            var formIndex = 0;
            var otr = this.getRowElement(oa);
            if (otr) {
                formIndex = otr.getAttribute("formIndex");
            }
            return formIndex;
        },
        drawToolbar: function () {

        },
        draw: function () {
            $(this.containerBodyElement).html("");

            this.tableElement = document.createElement("table");
            this.tableElement.className = "table table-hover";
            $(this.containerBodyElement).append(this.tableElement);

            this.addTitleRecord();
            this.getData();

        },
        refreshIndex: function () {
            var self = this;
            self.formIndex = 0;
            var totalLen = this.tableElement.rows.length;
            for (var i = 1; i < totalLen; i++) {
                var oRow = this.tableElement.rows[i];
                oRow.setAttribute("formIndex", self.formIndex);
                $(oRow).find("input[type=text]").each(function (i) {
                    var inputName = $(this).attr("name");
                    if (inputName) {
                        console.log(inputName);
                        reg = new RegExp('\\[(.+?)\\]', "g");
                        var formIndex = self.getRowFormIndex($(this)[0]);
                        var newName = inputName.replace(reg, '[' + formIndex + ']');
                        $(this).attr("name", newName);
                        console.log(formIndex);
                        console.log(newName);
                    }
                });
                self.formIndex++;
            }


        }

    });
    $.fn.detail = function (options) {
        var config = $.extend({}, DetailView.DEFAULTS, options);
        var detail = new DetailView(this, config);
        return detail;
    };
})(jQuery)